package com.letianpai.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.letianpai.bean.SixContacts;
import com.letianpai.bean.UserContacts;

public class SeekContactsUtils {
    /*
     * 查找联系人
     */
    public static ArrayList<UserContacts> seekContacts(Context context,
                                                       String informaiton) {
        ArrayList<UserContacts> list = (ArrayList<UserContacts>) ContactsUtils
                .getName(context);
        ArrayList<UserContacts> list1 = search(informaiton, list);
        return list1;
    }

    /**
     * 按号码-拼音搜索联系人
     *
     * @param str
     */
    public static ArrayList<UserContacts> search(final String str,
                                                 final ArrayList<UserContacts> allContacts) {
        ArrayList<UserContacts> contactList = new ArrayList<UserContacts>();
        // 如果搜索条件以0 1 +开头则按号码搜索
        if (str.startsWith("0") || str.startsWith("1") || str.startsWith("+")) {
            for (UserContacts contact : allContacts) {
                if (contact.getNumber() != null && contact.getName() != null) {
                    if (contact.getNumber().get(0).contains(str)
                            || contact.getName().contains(str)) {
                        contactList.add(contact);
                    }
                }
            }
            return contactList;
        }

        // final ChineseSpelling finder = ChineseSpelling.getInstance();
        // finder.setResource(str);
        // final String result = finder.getSpelling();
        // 先将输入的字符串转换为拼音
        // final String result = PinYinUtil.getFullSpell(str);
        final String result = PinYin.getPinYin(str);
        for (UserContacts contact : allContacts) {
            if (contains(contact, result)) {
                contactList.add(contact);
            }
        }

        return contactList;
    }

    /**
     * 根据拼音搜索
     *
     * @param str
     *            正则表达式
     * @param pyName
     *            拼音
     * @param isIncludsive
     *            搜索条件是否大于6个字符
     * @return
     */
    public static boolean contains(UserContacts contact, String search) {
        if (TextUtils.isEmpty(contact.getName()) || TextUtils.isEmpty(search)) {
            return false;
        }

        boolean flag = false;

        // 简拼匹配,如果输入在字符串长度大于6就不按首字母匹配了
        if (search.length() < 6) {
            // String firstLetters = FirstLetterUtil.getFirstLetter(contact
            // .getName());
            // 获得首字母字符串
            String firstLetters = UnicodeGBK2Alpha
                    .getSimpleCharsOfString(contact.getName());
            // String firstLetters =
            // PinYinUtil.getFirstSpell(contact.getName());
            // 不区分大小写
            Pattern firstLetterMatcher = Pattern.compile("^" + search,
                    Pattern.CASE_INSENSITIVE);
            flag = firstLetterMatcher.matcher(firstLetters).find();
        }

        if (!flag) { // 如果简拼已经找到了，就不使用全拼了
            // 全拼匹配
            // ChineseSpelling finder = ChineseSpelling.getInstance();
            // finder.setResource(contact.getName());
            // 不区分大小写
            Pattern pattern2 = Pattern
                    .compile(search, Pattern.CASE_INSENSITIVE);
            Matcher matcher2 = pattern2.matcher(PinYin.getPinYin(contact
                    .getName()));
            flag = matcher2.find();
        }

        return flag;
    }

    /*
     * 获取联系人姓氏最多的6个
     */
    public static List<SixContacts> getName(Context context) {
        List<SixContacts> array = new ArrayList<SixContacts>();
        ArrayList<String> nameList = new ArrayList<String>();
        ArrayList<SixContacts> list = new ArrayList<SixContacts>();

        ContentResolver cr = context.getContentResolver();
        final String[] PHONES_PROJECTION = new String[] { Phone.DISPLAY_NAME,
                Phone.NUMBER, Photo.PHOTO_ID, Phone.CONTACT_ID };
        Cursor phoneCursor = cr.query(Phone.CONTENT_URI, PHONES_PROJECTION,
                null, null, null);
        phoneCursor.moveToFirst();
        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {
                UserContacts us = new UserContacts();
                // 得到联系人名称
                String contactName = phoneCursor.getString(0);

                String a = contactName.substring(0, 1);

                nameList.add(a);
            }
        }
        Map<String, Integer> elementsCount = new HashMap<String, Integer>();
        for (String name : nameList) {
            Integer i = elementsCount.get(name);
            if (i == null) {
                elementsCount.put(name, 1);
            } else {
                elementsCount.put(name, i + 1);
            }
        }
        for (String s : elementsCount.keySet()) {
            SixContacts sc = new SixContacts();
            sc.setName(s);
            sc.setNumber(elementsCount.get(s));
            list.add(sc);
        }
        int tem = 0;
        String temname = null;
        for (int i = 0; i < list.size(); i++) {
            for (int j = i; j < list.size(); j++) {
                if (list.get(i).getNumber() < list.get(j).getNumber()) {
                    tem = list.get(i).getNumber();
                    SixContacts c = new SixContacts();
                    temname = list.get(i).getName();
                    c.setName(list.get(j).getName());
                    c.setNumber(list.get(j).getNumber());
                    list.set(i, c);
                    SixContacts s = new SixContacts();
                    s.setName(temname);
                    s.setNumber(tem);
                    list.set(j, s);
                }
            }
        }
        if(list.size()>5){
            array = list.subList(0, 6);
        }else{
            array = list;
        }
       
        return array;
    }

    /*
     * 查询家人
     */
    public static int getFamily(Context context) {
        int m = 0;
        ContentResolver cr = context.getContentResolver();
        ArrayList<String> nameList = new ArrayList<String>();

        final String[] PHONES_PROJECTION = new String[] { Phone.DISPLAY_NAME,
                Phone.NUMBER, Photo.PHOTO_ID, Phone.CONTACT_ID };
        Cursor phoneCursor = cr.query(Phone.CONTENT_URI, PHONES_PROJECTION,
                null, null, null);
        phoneCursor.moveToFirst();
        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {
                UserContacts us = new UserContacts();
                // 得到联系人名称
                String contactName = phoneCursor.getString(0);
                nameList.add(contactName);
            }
        }
        for (int i = 0; i < nameList.size(); i++) {
            if (nameList.get(i).contains("姨") || nameList.get(i).contains("妈")
                    || nameList.get(i).contains("爸")
                    || nameList.get(i).contains("外婆")
                    || nameList.get(i).contains("外公")
                    || nameList.get(i).contains("奶奶")
                    || nameList.get(i).contains("爷爷")
                    || nameList.get(i).contains("妹")
                    || nameList.get(i).contains("弟")
                    || nameList.get(i).contains("姐")
                    || nameList.get(i).contains("哥")
                    || nameList.get(i).contains("叔")
                    || nameList.get(i).contains("舅")) {
                m++;
            }
        }
        return m;
    }

    /*
     * 查询家人的信息
     */
    public static ArrayList<UserContacts> seekFamily(Context context) {
        ContentResolver cr = context.getContentResolver();
        ArrayList<UserContacts> nameList = new ArrayList<UserContacts>();
        ArrayList<UserContacts> callList = new ArrayList<UserContacts>();
        final String[] PHONES_PROJECTION = new String[] { Phone.DISPLAY_NAME,
                Phone.NUMBER, Photo.PHOTO_ID, Phone.CONTACT_ID };
        Cursor phoneCursor = cr.query(Phone.CONTENT_URI, PHONES_PROJECTION,
                null, null, null);
        phoneCursor.moveToFirst();
        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {
                UserContacts us = new UserContacts();
                ArrayList<String> number = new ArrayList<String>();
                // 得到手机号码
                String phoneNumber = phoneCursor.getString(1);
                // 当手机号码为空的或者为空字段 跳过当前循环
                if (TextUtils.isEmpty(phoneNumber))
                    continue;
                // 得到联系人名称
                String contactName = phoneCursor.getString(0);
                // 得到联系人ID
                Long contactid = phoneCursor.getLong(3);

                us.setName(contactName);
                number.add(phoneNumber);
                us.setUserId(contactid + "");
                us.setNumber(number);
                us.setPlace(ContactsUtils.queryplace(context, phoneNumber));
				/*
				 * if (null != contactName) { Uri uri = Uri
				 * .parse("content://com.android.contacts/data/phones/filter/" +
				 * contactName); Cursor cursor2 = cr.query(uri, new String[] {
				 * "photo_id" }, null, null, null);
				 *
				 * if (cursor2.moveToFirst()) {
				 *
				 * String phot_ID = cursor2.getString(0); if (null != phot_ID) {
				 * Cursor cursor3 = cr.query( ContactsContract.Data.CONTENT_URI,
				 * new String[] { "data15" }, "ContactsContract.Data._ID=" +
				 * phot_ID, null, null); us.setPictureId(phot_ID); if
				 * (cursor3.moveToFirst()) { byte[] photoicon =
				 * cursor3.getBlob(0);
				 *
				 * ByteArrayInputStream inputStream = new ByteArrayInputStream(
				 * photoicon);
				 *
				 * Bitmap contactPhoto = BitmapFactory
				 * .decodeStream(inputStream); us.setPicture(contactPhoto); }
				 * cursor3.close();
				 *
				 * } }
				 *
				 * cursor2.close();
				 *
				 * }
				 */

                callList.add(us);
            }
        }
        for (int i = 0; i < callList.size(); i++) {
            if (callList.get(i).getName().contains("姨")
                    || callList.get(i).getName().contains("妈")
                    || callList.get(i).getName().contains("爸")
                    || callList.get(i).getName().contains("外婆")
                    || callList.get(i).getName().contains("外公")
                    || callList.get(i).getName().contains("奶奶")
                    || callList.get(i).getName().contains("爷爷")
                    || callList.get(i).getName().contains("妹")
                    || callList.get(i).getName().contains("弟")
                    || callList.get(i).getName().contains("姐")
                    || callList.get(i).getName().contains("哥")
                    || callList.get(i).getName().contains("叔")
                    || callList.get(i).getName().contains("舅舅")
                    || callList.get(i).getName().contains("舅妈")) {
                nameList.add(callList.get(i));
            }
        }
        return nameList;
    }
}
